<template>
  <div class="body">
    <div class="top">
      <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
        <div ref="scrollContainer" class="scrollContainer">
          <el-table ref="top-table" class="top-table" empty-text="暂无数据" :data="listOne" :row-class-name="tableRowClassName" :max-height="tableOneMaxHeight" style="width: 100%;">
            <el-table-column prop="one" label="总拣配单数" />
            <el-table-column prop="two" label="该port拣配单数" />
            <el-table-column prop="three" label="总出库托数" />
            <el-table-column prop="four" label="该port出库托数" />
          </el-table>
        </div>
      </dv-border-box-10>
    </div>
    <div class="center">
      <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
        <div class="content-title">当前Port物料</div>
        <div ref="scrollContainer" class="scrollContainer">
          <el-table ref="center-table" empty-text="暂无数据" :data="listTwo" :row-class-name="tableRowClassName" :max-height="tableTwoMaxHeight" style="width: 100%;">
            <el-table-column prop="outBoundOrderCode" label="拣配单" />
            <el-table-column prop="customer" label="客户名称" />
            <el-table-column prop="parentPalletCode" label="母托条码" />
            <el-table-column prop="productNo" label="料号" />
            <el-table-column prop="partnerProductNo" label="客户物料编码" />
            <!-- <el-table-column prop="five" label="物料描述" /> -->
            <el-table-column prop="qty" label="该托总数量" />
            <el-table-column prop="bandingType" label="打带类型" />
            <el-table-column prop="wrappingQty" label="裹膜圈数" />
            <el-table-column prop="createTime" label="创建时间" />
            <!-- <el-table-column prop="seven" label="是否需要打带" />
            <el-table-column prop="eight" label="是否已经打带" />
            <el-table-column prop="nine" label="是否需要裹膜" />
            <el-table-column prop="ten" label="是否已经裹膜" />
            <el-table-column prop="eleven" label="备货需求时间"/>
            <el-table-column prop="twelve" label="发货需求时间"/>
            <el-table-column prop="thirteen" label="灯号" /> -->
          </el-table>
        </div>  
      </dv-border-box-10>
    </div>
    <div class="bottom">
      <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
        <div ref="scrollContainer" class="scrollContainer">
          <el-table ref="bottom-table" empty-text="暂无数据" :data="listThree" :row-class-name="tableRowClassName" :max-height="tableThreeMaxHeight" style="width: 100%;">
            <el-table-column prop="location" label="设备名称" />
            <el-table-column prop="status" label="状态" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="errorMessage" label="异常信息" />
          </el-table>
        </div>
      </dv-border-box-10>
    </div>
  </div>
</template>

<script>
import { EventSourcePolyfill } from 'event-source-polyfill'
export default {
  props: {
    port: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      listOne: [],
      listTwo: [],
      listThree: [],
      tableOneMaxHeight: 0, // 动态计算的高度
      tableTwoMaxHeight: 0, // 动态计算的高度
      tableThreeMaxHeight: 0, // 动态计算的高度
      timer: null,
      es: null
    }
  },
  mounted() {
    this.getHead()
    this.initAutoScroll()
    this.createSSE()
  },
  beforeDestroy() {
    if (this.timer) clearTimeout(this.timer)
    if (this.es) {
      this.es.close(); // 在组件销毁时关闭连接
    }
  },
  methods: {
    // getData() {
    //   console.log(this.listOne)
    //   console.log(this.listTwo)
    //   console.log(this.listThree)
    // },
    createSSE() {
      const baseURL = process.env.VUE_APP_BASE_API
      this.es = new EventSourcePolyfill(`${baseURL}api/sse/outboundDashboard`)
      this.es.onopen = () => {
        console.log('连接成功')
      }
      this.es.onclose = () => {
        console.log('连接断开')
      }
      this.es.onmessage = (e) => {
        const parsedData = JSON.parse(e.data)
        console.log(parsedData)
        const portKey = String(this.port).toUpperCase()
        // table1
        const mapOne = parsedData.data?.outboundRecordVO?.portOrderMap || {}
        const mapTwo = parsedData.data?.outboundRecordVO?.outboundCount || {}
        if (mapOne[portKey] !== undefined && mapTwo[portKey] !== undefined) {
          const tableOneItem = {
            one: parsedData.data?.outboundRecordVO?.orderCount,
            two: mapOne[portKey],
            three: parsedData.data?.outboundRecordVO?.outboundTotalCount,
            four: mapTwo[portKey]
          }
          this.listOne = [tableOneItem]
        }
        // table2
        const mapThree = parsedData.data?.outboundRecordVO?.outBoundInfoMap || {}
        if (mapThree[portKey] !== undefined) {
          this.listTwo = mapThree[portKey]
        }
        // table3
        this.listThree = parsedData.data.errorRecords || []
        this.getHeight()
      }
      this.es.onerror = (err) => {
        // this.es.close()
        this.handleError()
        console.log(err)
      }
    },
    handleError() {
      if (this.es.readyState === EventSourcePolyfill.CLOSED) {
        this.es.close()
        this.createSSE()
      } else if (this.es.readyState === EventSourcePolyfill.CONNECTING) {
        console.log('正在重连中')
      }
    },
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      } else {
        return 'success-row'
      }
    },
    getHead() {
      this.$nextTick(() => {
        const head = document.getElementsByClassName('el-table__header-wrapper')
        this.tableOneMaxHeight = head[0].offsetHeight * 2
        this.tableTwoMaxHeight = head[1].offsetHeight * 2
        this.tableThreeMaxHeight = head[2].offsetHeight * 2
      })
    },
    getHeight() {
      this.$nextTick(() => {
        const head = document.getElementsByClassName('el-table__header-wrapper')
        if (this.listOne.length === 0) {
          this.tableOneMaxHeight = head[0].offsetHeight * 2
        }
        if (this.listTwo.length === 0) {
          this.tableTwoMaxHeight = head[1].offsetHeight * 2 
        }
        if (this.listThree.length === 0) {
          this.tableThreeMaxHeight = head[2].offsetHeight * 2
        }
        // 步数
        const box = document.getElementsByClassName('el-table__body-wrapper')
        const boxStep = document.getElementsByClassName('el-table__body')
        const targetScrollTop = (box[0].scrollTop + boxStep[0]?.children[1]?.children[0]?.offsetHeight) || 0
        const targetScrollCenter = (box[1].scrollTop + boxStep[1]?.children[1]?.children[0]?.offsetHeight) || 0
        const targetScrollBottom = (box[2].scrollTop + boxStep[2]?.children[1]?.children[0]?.offsetHeight) || 0
        // ------
        const top = document.querySelector('.top')
        const center = document.querySelector('.center')
        const centerTitle = document.querySelector('.content-title')
        const bottom = document.querySelector('.bottom')
        const topHeight = top.children[0].children[5].offsetHeight
        const centerHeight = center.children[0].children[5].offsetHeight
        const centerTitleHeight = centerTitle.offsetHeight
        const bottomHeight = bottom.children[0].children[5].offsetHeight
        if (topHeight && this.tableOneMaxHeight === head[0].offsetHeight * 2) {
          this.tableOneMaxHeight = Math.floor(topHeight / targetScrollTop) * targetScrollTop;
        }
        if (centerHeight && this.tableTwoMaxHeight === head[1].offsetHeight * 2) {
          const adjustedCenterHeight = centerHeight - centerTitleHeight;
          this.tableTwoMaxHeight = Math.floor(adjustedCenterHeight / targetScrollCenter) * targetScrollCenter;
        }
        if (bottomHeight && this.tableThreeMaxHeight === head[2].offsetHeight * 2) {
          this.tableThreeMaxHeight = Math.floor(bottomHeight / targetScrollBottom) * targetScrollBottom;
        }
      })
    },
    initAutoScroll() {
      this.$nextTick(() => {
        const t = 3000 // 滚动间隔时间
        const box = document.getElementsByClassName('el-table__body-wrapper')
        const content = document.getElementsByClassName('el-table__body')
        // 定义一个平滑滚动的函数
        const smoothScroll = (element, target) => {
          const start = element.scrollTop
          const change = target - start
          const duration = 1500 // 滚动动画持续时间
          let startTimestamp = null
          const step = (timestamp) => {
            if (!startTimestamp) startTimestamp = timestamp
            const time = timestamp - startTimestamp
            const current = easeInOutCubic(time, start, change, duration)
            element.scrollTop = current
            if (time < duration) {
              requestAnimationFrame(step)
            }
          }
          requestAnimationFrame(step)
        }
        // 缓动函数，用于平滑滚动
        const easeInOutCubic = (t, b, c, d) => {
          t /= d / 2
          if (t < 1) return c / 2 * t * t * t + b
          t -= 2;
          return c / 2 * (t * t * t + 2) + b
        }
        this.timer = setInterval(() => {
          for (let i = 0; i < box.length; i++) {
            // const rows = content[i].querySelectorAll('.el-table__row') // 获取所有行
            // const currentRow = rows[Math.floor(box[i].scrollTop / box[i].offsetHeight)] // 当前行
            // // console.log(box[1].scrollTop)
            // // console.log(currentRow.offsetHeight)
            // if (currentRow) {
            //   const targetScrollTop = box[i].scrollTop + currentRow.offsetHeight // 当前行的高度
            //   if (targetScrollTop >= content[i].scrollHeight - box[i].offsetHeight) {
            //     smoothScroll(box[i], 0) // 如果到达底部，滚动到顶部
            //   } else {
            //     smoothScroll(box[i], targetScrollTop) // 滚动到当前行的高度
            //   }
            // } else {
            //   smoothScroll(box[i], 0) // 如果没有当前行，滚动到顶部
            // }
            const wrapper = box[i]
            const contentEl = content[i]
            const rows = Array.from(contentEl.querySelectorAll('.el-table__row'))
            const scrollTop = wrapper.scrollTop
            const wrapperHeight = wrapper.offsetHeight
            const contentHeight = contentEl.scrollHeight
            let currentIndex = 0
            for (let j = 0; j < rows.length; j++) {
              if (rows[j].offsetTop <= scrollTop) {
                currentIndex = j
              } else {
                break
              }
            }
            const nextIndex = currentIndex + 1
            let targetScrollTop
            if (nextIndex >= rows.length || scrollTop + wrapperHeight >= contentHeight - 1) {
              targetScrollTop = 0
            } else {
              targetScrollTop = rows[nextIndex].offsetTop
            }
            smoothScroll(wrapper, targetScrollTop)
          }
        }, t)
      })
    }
  }
}
</script>

<style scoped lang="less">
.body {
  .scrollContainer {
    overflow: scroll;
    /deep/ .el-table {
      height: 100% !important;
    }
  }
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 10px 5px;
  gap: 10px;
  .top {
    height: 10%;
    box-sizing: border-box;
  }
  .center {
    height: 50%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .content-title {
      box-sizing: border-box;
      color: #fff;
      text-align: center;
      font-size: 1.8rem;
    }
  }
  .bottom {
    box-sizing: border-box;
    height: 40%;
  }
}

// ------------------------------el-table---------------------
// el-table的margin
/deep/ .el-table {
  margin: 0 !important;
}
// el-tablk的宽度占满
/deep/ .el-table__body {
  width: 100% !important;
}

/deep/ tr td .cell {
  font-size: larger !important;
}

.el-table__body tr:hover > td {
  background-color: #1f68ddc0 !important;
}

.el-table th.el-table__cell {
  /* color: #05c3ff; */
  background-color: rgba(8, 119, 223, 0.6);
}

/deep/ .el-table th.el-table__cell > .cell {
  font-size: 23px !important;
}

.el-table--border {
  border: none;
}

.el-table,
.el-table__expanded-cell {
  background-color: transparent;
}

/deep/ .el-table__body-wrapper {
  background-color: rgba(19, 95, 236, 0.2) !important;
}

.el-table th,
.el-table tr,
.el-table td {
  background-color: transparent;
  color: #fff;
  border-color: transparent !important;
}

/deep/.el-table .warning-row {
  background: rgba(38, 66, 105, 0.5) !important;
}

/deep/.cell {
  text-align: center;
}

/deep/.el-table .success-row {
  //这里可以修改颜色
  background-image: linear-gradient(
    to left,
    rgba(3, 58, 141, 0.685) 0%,
    rgba(15, 30, 56, 0.8) 65%,
    rgba(22, 58, 109, 0.699) 100%
  );
}

.el-table::before {
  display: none !important;
}

.content-border ::-webkit-scrollbar {
  width: 0px; /* 设置滚动条的宽度 */
}
</style>
